home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: char* still alive after free ???
- Date: Mon, 15 Apr 96 18:12:11 GMT
- Organization: none
- Message-ID: <829591931snz@genesis.demon.co.uk>
- References: <317269EA.11BB93C2@studbox.uni-stuttgart.de>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <317269EA.11BB93C2@studbox.uni-stuttgart.de>
- Markus.Heller@studbox.uni-stuttgart.de "Markus Heller" writes:
-
- >Hi,
- >
- >I have a global variable :
- >
- >char *text=NULL;
- >
- >I want to use it to store different "strings" (at diffreent times).
- >E.g., if I want to sore 10 characters in text, I do a
- >text=(char *) malloc(10*sizeof(char));
-
- That's OK but why not write it simply as:
-
- text = malloc(10);
-
- which is much clearer IMHO.
-
- >When I want to use text to store 3 other characters, I first do a
- >free(text); text=NULL; and finally a
-
- The text = NULL; is redundant.
-
- >text=(char *) malloc(3*sizeof(char));
- >But to my surprise there are still the 4thh to 10th charcter of
- >text contained before the free(text)/malloc... ???
-
- How can you tell? It is illegal to access beyond text[2] but clearly you
- have done so and have as a consequence invoked undefined behaviour. That
- means anything can happen including what you saw.
-
- By calling free() you're telling the system that it can reuse the memory
- occupied by the object you passed a pointer to. It doesn't have to
- wipe that memory or make it inaccessible so you're just reading the
- last data that was put in it. You've no guarantees that that data won't have
- changed, it just hadn't in your case.
-
- >This happens under linux, but why ?
-
- That's just the way the Linux malloc functions worked in that case. When you
- malloc an object (such as an array of char in this case) its contents
- are indeterminate. You must write some data to it before you can legally
- read it.
-
- >(what I want to to is to get filenames from the user and then open those
- > files by a function to which I pass the file name..)
-
- There's nothing here that stops you doing that.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-